<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">


<head>
  <meta charset="utf-8">
  <title>注册 - Ruidao Exam</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css" th:href="@{static/layuiadmin/layui/css/layui.css}"
    media="all">
  <link rel="stylesheet" href="../../layuiadmin/style/admin.css" th:href="@{static/layuiadmin/style/admin.css}"
    media="all">
  <link rel="stylesheet" href="../../layuiadmin/style/login.css" th:href="@{static/layuiadmin/style/login.css}"
    media="all">
  <link rel="stylesheet" href="../../css/mail.css" th:href="@{static/css/mail.css}">
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="../../js/Particleground.js" th:src="@{static/js/Particleground.js}"></script>
  <script type='text/javascript' src='../js/cropper.min.js' th:src="@{static/js/cropper.min.js}"></script>
	<link rel="stylesheet" type="text/css" href="../css/cropper.min.css" th:href="@{static/css/cropper.min.css}"/>
	<link rel="stylesheet" type="text/css" href="../css/ImgCropping.css" th:href="@{static/css/ImgCropping.css}"/>
  <script type="text/javascript">
  	var currentemail = "";
  </script>
  <style>
    body {
      height: 100%;
      overflow: hidden;
    }

    canvas {
      z-index: -1;
      position: absolute;
    }
  </style>
  <script>
    $(document).ready(function () {
      //粒子背景特效
      $('body').particleground({
        dotColor: '#5cbdaa',
        lineColor: '#5cbdaa'
      });
    });
  </script>

</head>

<body>

<!--图片裁剪框 start-->
<div style="display: none" class="tailoring-container">
    <div class="black-cloth" onclick="closeTailor(this)"></div>
    <div class="tailoring-content">
        <div class="tailoring-content-one">
           <!-- <label title="上传图片" for="chooseImg" class="l2-btn choose-btn">
                <input type="file" accept="image/jpg,image/jpeg,image/png" name="file" id="chooseImg" class="hidden" onchange="selectImg(this)">
                		本地上传
            </label>-->
            <label title="拍照" class="layui-btn layui-btn-sm" id='capture' style="margin-left: 2%;">拍照</label>
            <label title="重拍" class="layui-btn layui-btn-sm" id='takeAgain' style="margin-left: 2%;">重拍</label>
            <div class="close-tailoring"  onclick="closeTailor(this)">×</div>
        </div>
        <div class="tailoring-content-two">
            <div class="tailoring-box-parcel">
                <video id="video" width="100%" height="100%" controls  style="float: left;" ></video>
                <canvas id="canvas" width="482px" height="448px" style="float: left;" hidden="hidden"></canvas>
                <div id="showImg" hidden="hidden" style="width: 100%;height:100%;">
                    <img id="tailoringImg">
                </div>
            </div>
            <div class="preview-box-parcel">
                <p>图片预览：</p>
                <div class="square previewImg"></div>
                <div class="circular previewImg"></div>
            </div>
        </div>
        <div class="tailoring-content-three">
            <button class="layui-btn layui-btn-sm cropper-reset-btn">复位</button>
            <button class="layui-btn layui-btn-sm cropper-rotate-btn">旋转</button>
            <button class="layui-btn layui-btn-sm cropper-scaleX-btn">换向</button>
            <button class="layui-btn layui-btn-sm sureCut" id="sureCut">确定</button>
        </div>
    </div>
</div>
<!--图片裁剪框 end-->

  <div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">
    <div class="layadmin-user-login-main">
      <div class="layadmin-user-login-box layadmin-user-login-header">
        <h2>欢迎来到Ruidao Exam</h2>
        <p>注册开启你的学习之旅吧~</p>
      </div>
      <div class="layadmin-user-login-box layadmin-user-login-body layui-form">
        <div class="layui-form-item">
          <!-- 刘斌 改变固有的图标-->
          <label class="layadmin-user-login-icon layui-icon mailicon icon-tubiao209"
            for="LAY-user-login-cellphone"></label>
          <input type="text" name="email" id="LAY-user-login-cellphone" lay-verify="email" placeholder="邮箱"
            class="layui-input">
        </div>
        <div class="layui-form-item">
          <div class="layui-row">
            <div class="layui-col-xs7">
              <label class="layadmin-user-login-icon layui-icon layui-icon-vercode"
                for="LAY-user-login-vercode"></label>
              <input type="text" name="vercode" id="LAY-user-login-vercode" lay-verify="required" placeholder="验证码"
                class="layui-input">
            </div>
            <div class="layui-col-xs5">
              <div style="margin-left: 10px;">
                <button type="button" class="layui-btn layui-btn-primary layui-btn-fluid"
                  id="getEmailCode">获取验证码</button>
              </div>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-password" for="LAY-user-login-password"></label>
          <input type="password" name="password" id="LAY-user-login-password" lay-verify="pass" placeholder="密码"
            class="layui-input">
        </div>
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-password" for="LAY-user-login-repass"></label>
          <input type="password" name="repass" id="LAY-user-login-repass" lay-verify="required" placeholder="确认密码"
            class="layui-input">
        </div>
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-username" for="LAY-user-login-nickname"></label>
          <input type="text" name="nickname" id="LAY-user-login-nickname" lay-verify="nickname" placeholder="昵称"
            class="layui-input">
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label" style="text-align: center">选择角色</label>
          <div class="layui-input-block" style="
            display: flex;
            justify-content: center;
            align-items: center;">
            <input type="radio" name="character" value="teacher" title="教师" lay-filter="role">
            <input type="radio" name="character" value="student" title="学生" lay-filter="role" checked="">
          </div> 
        </div>
        <div class="layui-form-item">
        <button style="display: block;" class="layui-btn layui-btn-fluid" id="RegisterFace" >录入人脸数据</button>
        </div>
        <div class="layui-form-item">
          <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="LAY-user-reg-submit">注 册</button>
        </div>
        <input type="text" id="base64url" style="display: none">
        <div class="layui-trans layui-form-item layadmin-user-login-other">
          <label>社交账号注册</label>
          <a href="javascript:;"><i class="layui-icon layui-icon-login-qq"></i></a>
          <a href="javascript:;"><i class="layui-icon layui-icon-login-wechat"></i></a>
          <a href="javascript:;"><i class="layui-icon layui-icon-login-weibo"></i></a>

          <a href="tologin" class="layadmin-user-jump-change layadmin-link layui-hide-xs">用已有帐号登入</a>
          <a href="tologin"
            class="layadmin-user-jump-change layadmin-link layui-hide-sm layui-show-xs-inline-block">登入</a>
        </div>
      </div>
    </div>

    <div class="layui-trans layadmin-user-login-footer">

      <p>© 2018 <a href="#" target="_blank">layui.com</a></p>
      <p>
        <span><a href="#" target="_blank">获取授权</a></span>
        <span><a href="#" target="_blank">在线演示</a></span>
        <span><a href="#" target="_blank">前往官网</a></span>
      </p>
    </div>

  </div>

  <script src="../../layuiadmin/layui/layui.js" th:src="@{static/layuiadmin/layui/layui.js}"></script>
  <script>
  	
  	$(function(){
  		/* $("#RegisterFace").click(function(){
      	alert(111);
      })*/
  	})
  	
  </script>
  <script>
    //获取验证码的动画
    function showtTime(nums) {

      if (nums == 0) {
        $("#getEmailCode").attr("disabled", false);
        $("#getEmailCode").html("获取验证码");
        nums = 60;
        return;
      } else {
        $("#getEmailCode").attr("disabled", true);
        $("#getEmailCode").html(nums + 's' + '后重发');
        nums--;
      }
      setTimeout(function () {
        showtTime(nums)
      }, 1000)
    }


    function checkEmail(){
      var mailinput = $("#LAY-user-login-cellphone").val()
      var flag=false;
      $.ajax({
          type:"POST",
          async:false,
          dataType:"text",
          data:{"email":mailinput},
          url:"/checkEmail",
          success:function(data){
            if(data=="1"){
              flag=true
              
            }else{
              layer.msg("邮箱已存在")
            }

          }

        })
        return flag;
    }

    function checkNickName(){
      var nicknameinput=$("#LAY-user-login-nickname").val()
      var flag=false;
      $.ajax({
          type:"POST",
          async:false,
          dataType:"text",
         data:{"nickname":nicknameinput},
          url:"/checkNickname",
          success:function(data){
            if(data=="1"){
              flag=true
              
            }else{
              layer.msg("昵称已存在")
            }

          }

        })
        return flag;
    }
    layui.config({
      base: '/static/layuiadmin/'  //静态资源所在路径
    }).extend({
      index: 'lib/index' //主入口模块
    }).use(['index', 'user'], function () {
      var $ = layui.$
        , setter = layui.setter
        , admin = layui.admin
        , form = layui.form
        , router = layui.router();

      form.render();
      form.on('radio(role)', function(data){
			  console.log(data.elem); //得到radio原始DOM对象
			  console.log(data.value); //被点击的radio的value值
        if(data.value=="student"){
          $("#RegisterFace").show();
        }else{
          $("#RegisterFace").hide();
        }
			});  
     
      
      $("#getEmailCode").click(function () {

        var mailverify = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
        var mailinput = $("#LAY-user-login-cellphone").val()
        if (mailinput == "") {
          layer.msg("请输入邮箱")
          return
        }
        if (!mailverify.test(mailinput)) {
          layer.msg("邮箱格式不正确")
          return
        } else {
        	if(!checkEmail()){
        	
        		return 
        	}
          var nums = 60;
          currentemail = mailinput;
          showtTime(nums);
          $.ajax({
            url: "/getverifyemail",
            type: "POST",
            data: { "receiver": mailinput },
            dataType: "text",
            success: function (data) {
              if (data != "1") {
                layer.msg("啊偶，系统出现了一丝丝小问题~")
              }


            },
            error: function () {
              layer.msg("啊偶，系统出现了一丝丝小问题~")
            }
          })

        }
      })

  
      $("#LAY-user-login-cellphone").blur(checkEmail)
      $("#LAY-user-login-nickname").blur(checkNickName)

      //提交
      form.on('submit(LAY-user-reg-submit)', function (obj) {
        var field = obj.field;
        //  console.log(JSON.stringify(field))
        //确认密码
        if (field.password !== field.repass) {
          return layer.msg('两次密码输入不一致');
        }
        if(!checkEmail()){
          return false
        }
        if(!checkNickName()){
          return false
        }
        //降低安全性验证
      	if(field.character=="student"&($("#base64url").val())==""){
        	return layer.msg("请上传人脸数据！")
     	} 

        // //请求接口
        // admin.req({
        //   url: layui.setter.base + 'json/user/reg.js' //实际使用请改成服务端真实接口
        //   , data: field
        //   , done: function (res) {
        //     layer.msg('注册成功', {
        //       offset: '15px'
        //       , icon: 1
        //       , time: 1000
        //     }, function () {
        //       location.hash = '/user/login'; //跳转到登入页
        //     });
        //   }
        // });
        var email = field.email
        var vercode = field.vercode
        var password = field.password
        var repass = field.repass
        var nickname = field.nickname
        var character = field.character
        var base64url=$("#base64url").val()
        if(currentemail != $("#LAY-user-login-cellphone").val()){
        	layer.msg("请勿更改邮箱！");
        	return false;
        }
        console.log(vercode);
        $.ajax({
          url: "/checkRegister",
          type: "POST",
          dataType: "text",
          data: {
            "email": email,
            "vercode": vercode,
            "password": password,
            "repass": repass,
            "nickname": nickname,
            "character": character,
            "base64url":base64url
          },
          success: function (data) {
            if (data == 1) {
              layer.msg("注册成功。正在转向登录界面");
              setTimeout(function(){
                window.location.href="tologin"
              },1000)
              
            } else {
              layer.msg("验证码错误");
            }
          },
          error: function (e) {
            layer.msg("系统异常");
          }
        });


        return false;
      });

    });
  </script>
  <script>

    //弹出框水平垂直居中
    (window.onresize = function () {
        var win_height = $(window).height();
        var win_width = $(window).width();
        if (win_width <= 768){
            $(".tailoring-content").css({
                "top": (win_height - $(".tailoring-content").outerHeight())/2,
                "left": 0
            });
        }else{
            $(".tailoring-content").css({
                "top": (win_height - $(".tailoring-content").outerHeight())/2,
                "left": (win_width - $(".tailoring-content").outerWidth())/2
            });
        }
    })();

    //图像上传
    function selectImg(file) {
        if (!file.files || !file.files[0]){
            return;
        }
        var reader = new FileReader();
        reader.onload = function (evt) {
            var replaceSrc = evt.target.result;
            //更换cropper的图片
            $('#tailoringImg').cropper('replace', replaceSrc,false);//默认false，适应高度，不失真

        }
        reader.readAsDataURL(file.files[0]);
        mediaStreamTrack && mediaStreamTrack.stop();
        $("#video").hide();
        $("#showImg").show();

    }
    //cropper图片裁剪
    $('#tailoringImg').cropper({
        aspectRatio: 1/1,//默认比例
        preview: '.previewImg',//预览视图
        guides: false,  //裁剪框的虚线(九宫格)
        autoCropArea: 0.5,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
        movable: false, //是否允许移动图片
        dragCrop: true,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
        movable: true,  //是否允许移动剪裁框
        resizable: true,  //是否允许改变裁剪框的大小
        zoomable: false,  //是否允许缩放图片大小
        mouseWheelZoom: false,  //是否允许通过鼠标滚轮来缩放图片
        touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
        rotatable: true,  //是否允许旋转图片
        crop: function(e) {
            // 输出结果数据裁剪图像。
        }
    });

    //弹框
    $("#RegisterFace").on("click",function () {
      var email=$("#LAY-user-login-cellphone").val()
      var verifycode=$("#LAY-user-login-vercode").val()
      var password=$("#LAY-user-login-password").val()
      var repass=$("#LAY-user-login-repass").val()
      var nickname=$("#LAY-user-login-nickname").val()
      if(email==""||verifycode==""||password==""||repass==""||nickname==""){
        layer.msg("请先全部填完上述信息")
        return
      }
       takeImg()
    });

    //旋转
    $(".cropper-rotate-btn").on("click",function () {
        $('#tailoringImg').cropper("rotate", 45);
    });
    //复位
    $(".cropper-reset-btn").on("click",function () {
        $('#tailoringImg').cropper("reset");
    });
    //换向
    var flagX = true;
    $(".cropper-scaleX-btn").on("click",function () {
        if(flagX){
            $('#tailoringImg').cropper("scaleX", -1);
            flagX = false;
        }else{
            $('#tailoringImg').cropper("scaleX", 1);
            flagX = true;
        }
        flagX != flagX;
    });

    //裁剪后的处理
    $("#sureCut").on("click",function () {
        var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
        var base64url = cas.toDataURL('image/png'); //转换为base64地址形式
        base64url=base64url.replace("\r","");
        $("#base64url").val(base64url)
        console.log(base64url)
        var datas={"base64url":base64url}
        $.ajax({
			url:'doPhotoRegister',
			type:'post',
			dataType:'text',
			async:false,
			data:datas,
			success:function(e){
				//alert(e);
				//window.location.href = 'toExamOver';
			},
			error:function(e){
				console.log(e);
  			layer.msg('出错了！');
			}
		});
        
        
        /*$.post("../Info",
        {
        	op:"takePhoto",
        	base64url:base64url 
        }, 
        function(data){
            var result=parseInt($.trim(data.result));
            if(result==-1){
                $.messager.show({title:"温馨提示",msg:"输入的信息不完整,确认后重新提交。",timeout:3000,showType:'slide'})
            }else if(result>0){
                $.messager.show({title:"成功提示",msg:"头像更新成功",timeout:3000,showType:'slide'})
                //$('#attendance_info').css('color','green').text("已提交");
            }else{
                $.messager.alert("失败提示","头像更新失败，请稍后重试...",'error')
            }
        }, "JSON");*/
        //关闭裁剪框
        closeTailor();
    });
    //关闭裁剪框
    function closeTailor() {
        $(".tailoring-container").toggle();
        mediaStreamTrack && mediaStreamTrack.stop();
    }

    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    }

    let video = document.getElementById('video');
    let canvas = document.getElementById('canvas');
    let context = canvas.getContext('2d');
    var mediaStreamTrack
    function success(stream) {
        //兼容webkit核心浏览器
        let CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源
        mediaStreamTrack = stream.getTracks()[0];
        //video.src = CompatibleURL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    }

    function error(error) {
        alert('访问用户媒体设备失败,请尝试更换浏览器')
    }



    document.getElementById('capture').addEventListener('click', function () {
        context.drawImage(video, 0, 0, 480, 320);
        mediaStreamTrack && mediaStreamTrack.stop();
        $('#tailoringImg').cropper('replace', canvas.toDataURL("image/png"),false);//默认false，适应高度，不失真
        $("#video").hide();//隐藏拍照框
        $("#showImg").show()//将拍照结果显示
    })

    //请求拍照
    $("#takeAgain").bind("click", function(){
        takePhoto();
    });

    //开始拍照
    function takeImg(){
        $(".tailoring-container").toggle();
        takePhoto();
    }

    //请求摄像头
    function takePhoto() {
        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            //调用用户媒体设备, 访问摄像头
            getUserMedia({video : {width: 100, height: 100}}, success, error);
            $("#showImg").hide();//隐藏拍照结果显示框
            //$('#showImg').html('<img id="tailoringImg" hidden="hidden">')
            $("#video").show();//开启拍照框
        } else {
            alert('不支持访问用户媒体');
        }
    }
</script>
</body>

</html>